package com.yhuk.oauth.server.filter;

import org.apache.commons.lang.ArrayUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.oauth2.provider.ClientDetails;
import org.springframework.security.oauth2.provider.ClientDetailsService;
import org.springframework.security.oauth2.provider.token.TokenStore;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Set;

/**
 * @author xiaolang
 * @version 1.0.0
 */
public class LoginFilter implements Filter {
    private Logger logger = LoggerFactory.getLogger(LoginFilter.class);

    @Autowired
    ClientDetailsService clientDetailsService;
    @Autowired
    TokenStore tokenStore;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        logger.info("LoginFilter启动。。。。");
    }

    @Override
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) req;
        HttpServletResponse response = (HttpServletResponse) res;
        if(request.getServletPath().contains("/auth/token")||
                request.getServletPath().contains("/login") ||
                request.getServletPath().contains("/is_login")||
                request.getServletPath().contains("/sessionTest")){ //登录认证不拦截
            filterChain.doFilter(request,response);
            return;
        }
        logger.info("requestUrl:{}",request.getRequestURL().toString());
        ClientDetails clientDetails = clientDetailsService.loadClientByClientId(request.getParameter("clientId"));
        List<String> uris = new ArrayList<>(clientDetails.getRegisteredRedirectUri()); //重定向登录地址

        if(request.getSession().getAttribute("isLogin").equals(Boolean.TRUE)){  //去建立局部会话
            String token = request.getSession().getAttribute("token").toString();
            response.sendRedirect(uris.get(1)+"?token="+token);
        }
        else{
            response.sendRedirect(uris.get(0)); // 跳转到登录地址
        }
    }

    @Override
    public void destroy() {

    }
}
